/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.neilcsmith.praxis.live.experimental;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import net.neilcsmith.praxis.live.graph.Alignment;
import net.neilcsmith.praxis.live.graph.PraxisGraphScene;
import net.neilcsmith.praxis.live.graph.NodeWidget;
import net.neilcsmith.praxis.live.graph.PinWidget;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
//import org.openide.util.ImageUtilities;
import org.netbeans.api.settings.ConvertAsProperties;
import org.netbeans.api.visual.action.ConnectProvider;
import org.netbeans.api.visual.action.ConnectorState;
import org.netbeans.api.visual.widget.Scene;
import org.netbeans.api.visual.widget.Widget;


/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//net.neilcsmith.praxiside.graphtest//Graph//EN",
autostore = false)
public final class GraphTopComponent extends TopComponent {

    private static GraphTopComponent instance;
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
    private static final String PREFERRED_ID = "GraphTopComponent";
    private PraxisGraphScene scene;

    public GraphTopComponent() {
//        initComponents();
        setName(NbBundle.getMessage(GraphTopComponent.class, "CTL_GraphTopComponent"));
        setToolTipText(NbBundle.getMessage(GraphTopComponent.class, "HINT_GraphTopComponent"));
//        setIcon(ImageUtilities.loadImage(ICON_PATH, true));
        initGraph();

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables

    private void initGraph() {
        setLayout(new BorderLayout());
        scene = new PraxisGraphScene<String>();
        
        NodeWidget n = scene.addNode("Node 1", "Timer");
        n.setNodeType("core:timing:timer");
        n = scene.addNode("Node 2", "Delay");
        n.setNodeType("audio:timing:delay");
        n = scene.addNode("Node 3", "Output");
        n.setNodeType("audio:output");
        scene.addPin("Node 1", "Pin 1", "control", Alignment.Right);
        scene.addPin("Node 2", "Pin 1", "control", Alignment.Left);
        scene.addPin("Node 2", "Pin 2", "audio", Alignment.Right);
        scene.addPin("Node 3", "Pin 1", "audio", Alignment.Center);
        scene.connect("Node 1", "Pin 1", "Node 2", "Pin 1");
        scene.connect("Node 1", "Pin 1", "Node 2", "Pin 2");
        scene.connect("Node 2", "Pin 1", "Node 3", "Pin 1");
        scene.connect("Node 2", "Pin 2", "Node 3", "Pin 1");
        scene.connect("Node 1", "Pin 1", "Node 3", "Pin 1");


        JScrollPane pane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        pane.setViewportView(scene.createView());
        add(pane, BorderLayout.CENTER);
        add(scene.createSatelliteView(), BorderLayout.WEST);

    }

    
//    private void initGraph() {
//        setLayout(new BorderLayout());
//
//        scene = new Scene ();
//
//        scene.addChild (new LabelWidget (scene, "Press Enter key to invoke the action"));
//
//        InputMap inputMap = new InputMap ();
//        inputMap.put (KeyStroke.getKeyStroke (KeyEvent.VK_ENTER, 0, false), "myAction");
//
//        ActionMap actionMap = new ActionMap ();
//        actionMap.put ("myAction", new MyAction ());
//
//        scene.getActions ().addAction (ActionFactory.createActionMapAction (inputMap, actionMap));
//        JScrollPane pane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
//                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//        pane.setViewportView(scene.createView());
//        scene.getView().requestFocusInWindow();
//        add(pane, BorderLayout.CENTER);
//    }

    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link #findInstance}.
     */
    public static synchronized GraphTopComponent getDefault() {
        if (instance == null) {
            instance = new GraphTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the GraphTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized GraphTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(GraphTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof GraphTopComponent) {
            return (GraphTopComponent) win;
        }
        Logger.getLogger(GraphTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID
                + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_NEVER;
    }

    @Override
    public void componentOpened() {
        System.out.println("Graph Component Opened");
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                scene.getView().requestFocusInWindow();
            }
        });
        
    }

    @Override
    protected void componentActivated() {
        super.componentActivated();
        System.out.println("Graph Component Activated");
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                scene.getView().requestFocusInWindow();
            }
        });
    }


    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    Object readProperties(java.util.Properties p) {
        if (instance == null) {
            instance = this;
        }
        instance.readPropertiesImpl(p);
        return instance;
    }

    private void readPropertiesImpl(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    @Override
    protected String preferredID() {
        return PREFERRED_ID;
    }

    private static class MyAction extends AbstractAction {

        public MyAction () {
            super ("My Action");
        }

        public void actionPerformed (ActionEvent e) {
            JOptionPane.showMessageDialog (null, "My Action has been invoked");
        }
    }

        private class Provider implements ConnectProvider {
        private int edgeCount;



            public boolean isSourceWidget(Widget sourceWidget) {
                if (sourceWidget instanceof PinWidget) {
                    return true;
                } else {
                    return false;
                }
            }

            public ConnectorState isTargetWidget(Widget sourceWidget, Widget targetWidget) {
                if (sourceWidget instanceof PinWidget && targetWidget instanceof PinWidget) {
                    return ConnectorState.ACCEPT;
                } else {
                    return ConnectorState.REJECT;
                }
            }

            public boolean hasCustomTargetWidgetResolver(Scene scene) {
                return false;
            }

            public Widget resolveTargetWidget(Scene scene, Point sceneLocation) {
                return null;
            }

        @Override
            public void createConnection(Widget sourceWidget, Widget targetWidget) {
                edgeCount++;
                String id = "Edge " + edgeCount;
                scene.addEdge(id);
                scene.setEdgeSource(id, (String) scene.findObject(sourceWidget));
                scene.setEdgeTarget(id, (String) scene.findObject(targetWidget));
            }
        }


}
